const fs = require('fs');
const path = require('path');
const basePath = path.join(__dirname, '../mock');

module.exports = function proxyServer(req, res, next) {
    const mockLocalJs = filePath => {
        res.end(JSON.stringify(require(filePath)(req.body)));
        delete require.cache[require.resolve(filePath)];
    };

    const mockLocalFile = filePath => {
        res.end(fs.readFileSync(filePath, 'utf8'));
    };

    const reqPath = req.path;
    if (req.headers['x-requested-with']) {

        const relPath = path.join(basePath, reqPath);

        const filePaths = [
            `${relPath}.json`,
            `${relPath}/index.json`,
            `${relPath}.js`,
            `${relPath}/index.js`
        ];

        for (let filePath of filePaths) {
            if (fs.existsSync(filePath)) {
                console.log(`request: ${reqPath} mock to ${filePath}`);
                res.writeHead(200, {'Content-Type': 'text/html;charset:UTF-8'});
                if (filePath.endsWith('.js')) {
                    mockLocalJs(filePath);
                }
                else {
                    mockLocalFile(filePath);
                }
                return true;
            }
        }
    }
    return next();
};
